<template>
  <div class="scheduling_box">
    <a-tabs type="card" v-model:activeKey="activeFormKey" animated>
      <a-tab-pane tab="排产内容" key="preProductionSchedulingContent" :forceRender="true">
        <BasicForm @register="registerForm" ref="formRef">
          <template #masterPlanSlot="{ model, field }">
            <!-- <a-input-search
              v-model:value="model[field]"
              placeholder="请选择生产主计划"
              readonly
              :disabled="isDetail"
              @search="masterPlanOpen(model)"
            /> -->
            <a-button class="mgl-15" type="primary" @click="masterPlanOpen(model)"
              >新增需求</a-button
            >
          </template>
          <template #productionSchedulingSchemeSlot="{ model, field }">
            <a-input-search
              :disabled="isDetail"
              v-model:value="model[field]"
              placeholder="请选择排产方案"
              readonly  
              @search="openPsAlwaysScheduling"
            />
          </template>
          <template #formFooter="{ model, field }">
            <a-button
              class="mgl-15"
              color="success"
              @click="clickSchedulingOperation"
              v-if="hasPermission('ps:ps_planning_scheduling:calculate')"
              >排产作业</a-button
            >
          </template>
        </BasicForm>
      </a-tab-pane>
    </a-tabs>
    <!-- 子表单区域 -->
    <a-tabs
      type="card"
      class="my_tabs"
      v-model:activeKey="activeKey"
      animated
      @change="handleChangeTabs"
    >
      <template #rightExtra>
        <!-- <a-button color="success" class="mgl-15" @click="requestAddOrEdit">保存</a-button> -->
        <!-- <a-button type="primary" class="mgl-15" @click="clickSchedulingTableAdd"
          >新增</a-button
        >
        <a-button color="error" class="mgl-15" @click="clickSchedulingTableDel"
          >移除</a-button
        > -->
      </template>
      <a-tab-pane
        tab="排产需求"
        key="psPlanningSchedulingOrderContent"
        :forceRender="true"
      >
        <JVxeTable
          keep-source
          resizable
          ref="psPlanningSchedulingOrderContent"
          :rowNum="true"
          rowNumKey="srcDocLineNo"
          :loading="psPlanningSchedulingOrderContentTable.loading"
          :columns="psPlanningSchedulingOrderContentTable.columns"
          :dataSource="psPlanningSchedulingOrderContentTable.dataSource"
          :height="550"
          :rowSelection="true"
          :disabled="formDisabled"
          :toolbar="true"
          :asyncRemove="true"
          :toolbarConfig="toolbarConfig"
          @removed="removed"
          :pagination="pagination"
          @pageChange="pageChange"
        >         
         <template #toolbarSuffix>
            <a-form
              layout="inline"
              :model="formState"
              @finish="getList"
              :labelCol="{ span: 8 }"
              style="margin-bottom: 10px"
            >
              <a-form-item label="订单编号">
                <a-input
                  v-model:value="formState.srcDocNo"
                  placeholder="请输入订单编号"
                  allowClear
                >
                </a-input>
              </a-form-item>
              <a-form-item label="产品编码">
                <a-input
                  v-model:value="formState.productCode"
                  placeholder="请输入产品编码"
                  allowClear
                >
                </a-input>
              </a-form-item>
              <a-form-item label="订单交期">
                <a-range-picker v-model:value="formState.orderDeliveryDate" @change="changeOrderDeliveryDate" :valueFormat="'YYYY-MM-DD HH:mm:ss'"/>
              </a-form-item>
              <a-form-item>
                <a-button type="primary" html-type="finish">查询</a-button>
              </a-form-item>
            </a-form>
          </template>
          <template #srcDocTypeSlot="props">
            {{ props.row.srcDocType === 1 ? '计划订单' : props.row.srcDocType === 2 ? '销售订单' : '生产工单' }}
          </template>
          <!-- @valueChange="valueChange"
          <template #orderSlot="props">
            <a-input-search
              @search="handleView(props.row)"
              readonly
              placeholder="请选择"
              v-model:value="props.row.PlanOrderCode"
            />
          </template>
          <template #srcDocNoSlot="props">
            <a-input
              v-model:value="props.row.srcDocNo"
              placeholder="请输入来源订单号"
              @pressEnter="saveOrUpdate(props.row, true)"
            />
          </template>
          <template #srcDocLineNoSlot="props">
            <a-input-number
              v-model:value="props.row.srcDocLineNo"
              placeholder="请输入行号"
              @pressEnter="saveOrUpdate(props.row, true)"
            />
          </template>
          <template #orderQuantitySlot="props">
            <a-input-number
              v-model:value="props.row.orderQuantity"
              placeholder="请输入订单数量"
              @pressEnter="saveOrUpdate(props.row, true)"
            />
          </template>
          <template #lastEndDischargeSlot="props">
            <a-input-number
              v-model:value="props.row.lastEndDischarge"
              placeholder="请输入上期未排量"
              @pressEnter="saveOrUpdate(props.row, true)"
            />
          </template>
          <template #totalProductionSlot="props">
            <a-input-number
              v-model:value="props.row.totalProduction"
              placeholder="请输入总需求数量"
              @pressEnter="saveOrUpdate(props.row, true)"
            />
          </template>
          <template #actualProductionSchedulingSlot="props">
            <a-input-number
              v-model:value="props.row.actualProductionScheduling"
              placeholder="请输入本次需排产数量"
              @pressEnter="saveOrUpdate(props.row, true)"
            />
          </template>
          <template #productNameSlot="props">
            <a-input-search
              v-model:value="props.row.productCode"
              placeholder="请选择产品编码"
              @search="handleView(props)"
            />
          </template> -->
          <!-- 操作按钮 -->
          <template #action="props">
            <a @click="handleEdit(props.row)">编辑</a>
            <a-divider type="vertical" v-if="hasPermission('ps:pre:scheduling:delete')" />
            <a-popconfirm title="确定删除吗？" @confirm="handleDelete([props.row])" v-if="hasPermission('ps:pre:scheduling:delete')">
              <a>删除</a>
            </a-popconfirm>
          </template>
        </JVxeTable>
      </a-tab-pane>
      <a-tab-pane tab="排产日志" key="productionSchedulingLog" :forceRender="true">
        <JVxeTable
          keep-source
          resizable
          ref="productionSchedulingLog"
          :loading="productionSchedulingLogTable.loading"
          :columns="productionSchedulingLogTable.columns"
          :dataSource="productionSchedulingLogTable.dataSource"
          :height="550"
          :disabled="formDisabled"
          :pagination="pagination2"
          :toolbar="true"
          @removed="removed"
          @pageChange="pageChange2"
        >
        <template #toolbarSuffix>
          <a-form
              layout="inline"
              :model="formState"
              @finish="getList2"
              :labelCol="{ span: 8 }"
              style="margin-bottom: 10px"
            >             
              <a-form-item>
                <a-button type="primary" html-type="finish">刷新</a-button>
              </a-form-item>
            </a-form>
          </template>
          <template #statusSlot="props">
            {{ props.row.status === 0 ? '运行中' : props.row.status === 1 ? '成功' : '失败' }}
          </template>
          <!-- 操作按钮 -->
          <!-- <template #action="props">
            <a @click="handleEdit(props.row)">编辑</a>
            <a-divider type="vertical" v-if="hasPermission('ps:scheduling:delete')" />
            <a-popconfirm title="确定删除吗？" @confirm="handleDelete([props.row])" v-if="hasPermission('ps:scheduling:delete')">
              <a>删除</a>
            </a-popconfirm>
          </template> -->
        </JVxeTable>
      </a-tab-pane>
      <!-- <a-tab-pane tab="模拟结果" key="simulatedResultRef" :forceRender="true">
        <JVxeTable
          keep-source
          resizable 
          ref="simulatedResultRef"
          :loading="simulatedResultTable.loading"
          :columns="simulatedResultTable.columns"
          :dataSource="simulatedResultTable.dataSource"
          :height="340"
          :rowNumber="false"
          :rowSelection="true"
          :disabled="formDisabled"
          :toolbar="false"
        />
      </a-tab-pane> -->
      <!-- <template v-slot:rightExtra>
      <a-button @click="clickSimulatedScheduling" v-if="hasPermission('ps:ps_planning_scheduling:calculate')">模拟排产</a-button>
        <a-button color="success" @click="clickDistributePlan" v-if="hasPermission('ps:ps_planning_scheduling:distribute')" class="m-4">下发计划</a-button>
    </template> -->
    </a-tabs>
    <!-- 方案选择 -->
    <psPreAlwaysSchedulingSelectModel
      @register="psAlwaysSchedulingRegModal"
      @getSelectResult="psAlwaysSchedulinghandleSuccess"
      v-bind="getBindValue"
    >
    </psPreAlwaysSchedulingSelectModel>
    <!-- 订单选择 -->
    <!-- <planOrerResultSelectModel @register="planOrderResultRegModal" @getSelectResult="planOrderResultHandleSuccess" v-bind="getBindValue" /> -->
    <!-- MPS生产主计划列表 -->
    <mpsSelectModel
      @register="mpsItemRegModal"
      @getSelectResult="mpsItemhandleSuccess"
      :multiple="true"
      v-bind="getBindValue"
    />
    <!-- 订单选择 -->
    <orderSelectModel
      @register="orderRegModal"
      @getSelectResult="orderhandleSuccess"
      :multiple="true"
      v-bind="getBindValue"
    />
    <!-- 计划订单选择 -->
    <planOrderListSelectModel  
      @register="registerPlanOrderModal"
      @getSelectResult="PlanOrderhandleSuccess"
      :multiple="true"
    />
    <!-- 选择总装排产计划 -->
    <arrangementPlansSelectModel
      @register="arrangementPlanRegModal"
      @getSelectResult="arrangementPlanhandleSuccess"
      :multiple="true"
      v-bind="getBindValue"
    />
    <!-- 选择MO列表 -->
    <finalAssemblyPlanOrderQGXSelectModel
      @register="registerMOListModal"
      @getSelectResult="MOListhandleSuccess"
      :multiple="true"
    />
    <!-- 料品 -->
    <materialSelectModel
      @register="materialRegModal"
      @getSelectResult="materialhandleSuccess"
      v-bind="getBindValue"
    ></materialSelectModel> 
    <!-- 子表编辑界面 -->
    <psPlanningSchedulingEdit @register="registerPlanningSchdulingEdit" @success="getSchedulingList" />
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive, onMounted } from "vue";
import { BasicModal, useModalInner, useModal } from "/@/components/Modal";
import { BasicForm, useForm } from "/@/components/Form/index";
import { JVxeTable } from "/@/components/jeecg/JVxeTable";
import { useJvxeMethod } from "/@/hooks/system/useJvxeMethods";
import {
  formSchema,
  psPrePlanningSchedulingOrderContentColumns,
  productionSchedulingLogColumns
} from "./PsPlanningScheduling.data.ts";
import {
  saveOrUpdate,
  psPlanningSchedulingOrderContentList,
  psPlanningSchedulingAvailableResourcesList,
  distributePlan,
  getMpsItemByMainIds,
  getArrangementItemByMainIds,
  // getSimulatedScheduling,
  schedulingList,
  schedulingDel,
  preCalculate,
  gerProductionSchedulingLogList
} from "./PsPlanningScheduling.api.ts";
import { VALIDATE_FAILED } from "/@/utils/common/vxeUtils";
import psPreAlwaysSchedulingSelectModel from "/@/views/components/psPreAlwaysSchedulingSelectModel.vue";
import orderSelectModel from "/@/views/components/orderSelectModel.vue";
// import planOrerResultSelectModel from '/@/views/components/planOrderResultSelectModel.vue';
import { useMessage } from "/@/hooks/web/useMessage";
import mpsSelectModel from "/@/views/components/mpsSelectModel.vue";
import arrangementPlansSelectModel from "/@/views/components/arrangementPlansSelectModel.vue";
import materialSelectModel from "/@/views/components/materialSelectModel.vue";
import psPlanningSchedulingEdit from "./components/PsPlanningSchedulingEdit.vue";
import finalAssemblyPlanOrderQGXSelectModel from "/@/views/components/finalAssemblyPlanOrderQGXSelectModel.vue";
import planOrderListSelectModel from '/@/views/components/planOrderListSelectModel.vue';
import { useLoading } from "/@/components/Loading";
import { usePermission } from "/@/hooks/web/usePermission";
const { hasPermission } = usePermission();
const [openFullLoading, closeFullLoading] = useLoading({
  tip: "正在进行模拟排产...",
});
// 分页器
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});
const pagination2 = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});
// 工具栏的按钮配置
const toolbarConfig = reactive({
  // add 新增按钮；remove 删除按钮；clearSelection 清空选择按钮
  btn: [ 'remove', 'clearSelection'],
  // btn: [],
});
const formState = reactive({
  srcDocNo: '',
  productCode: '',
  orderDeliveryDate:[]
});
// Emits声明
const emit = defineEmits(["register", "success"]);
const isUpdate = ref(true);
const isDetail = ref<boolean>(false);
const formDisabled = ref(false);
const refKeys = ref(["psPlanningSchedulingOrderContent"]);
const activeKey = ref("psPlanningSchedulingOrderContent");
const activeFormKey = ref("preProductionSchedulingContent");
const psPlanningSchedulingOrderContent = ref();
const tableRefs = {
  psPlanningSchedulingOrderContent,
};
interface Props {
  // planId: number | string;
}
const operatFormItem = ref<any>(null);
const propsData = defineProps<Props>();
const psPlanningSchedulingOrderContentTable = reactive({
  loading: false,
  dataSource: <Array<any>>[],
  columns: psPrePlanningSchedulingOrderContentColumns,
});

//表单配置
const [
  registerForm,
  { setProps, resetFields, setFieldsValue, getFieldsValue, validate, validateFields },
] = useForm({
  labelWidth: 100,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: {
    span: 6,
  },
});
const $message = useMessage();
const handleChangeTabs = async (activeKey) => {
  if (activeKey === 'productionSchedulingLog') {
    await getSchedulingListTwo();
  }
};
//方法配置
const [ handleSubmit, requestSubTableData, formRef] = useJvxeMethod(
  requestAddOrEdit,
  classifyIntoFormData,
  tableRefs,
  activeKey,
  refKeys
);
onMounted(() => {
  getSchedulingList();
});
async function reset() {
  await resetFields();
  activeKey.value = "psPlanningSchedulingOrderContent";
  psPlanningSchedulingOrderContentTable.dataSource = [];
  simulatedResultTable.dataSource = [];
}
const productionSchedulingLogTable = reactive({
  loading: false,
  dataSource: <Array<any>>[],
  columns: productionSchedulingLogColumns,
});
function classifyIntoFormData(allValues) {
  let main = Object.assign({}, allValues.formValue);
  return {
    ...main, // 展开
    psPlanningSchedulingOrderContentList: allValues.tablesValue[0].tableData,
  };
}
let index: number | null = null;
//打开选择料品
function handleView(props) {
  index = props.params.$rowIndex;
  openMaterialModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
function changeOrderDeliveryDate(arr) {
  if(arr && arr.length>0){
    formState.orderDeliveryDateStats = arr[0];
    formState.orderDeliveryDateEnd = arr[1];
  } else {
    delete formState.orderDeliveryDateStats;
    delete formState.orderDeliveryDateEnd;
  }  
}
function removed(row) {
  handleDelete(row.deleteRows);
}
// 排产工作台详情列表
async function getSchedulingList() {
  // 处理分页参数
  let tempParams = {
    column: "createTime",
    order: "desc",
    pageNo: pagination.current,
    pageSize: pagination.pageSize,
  };
  const params = Object.assign(tempParams, formState);
  delete params.orderDeliveryDate;  
  let res = await schedulingList(tempParams);
  psPlanningSchedulingOrderContentTable.dataSource = psPlanningSchedulingOrderContent.value!.getTableData();
  psPlanningSchedulingOrderContentTable.dataSource = res.records;
  pagination.total = res.total;
}
async function getSchedulingListTwo() {
  // 处理分页参数
  let tempParams = {
    column: "createTime",
    order: "desc",
    pageNo: pagination2.current,
    pageSize: pagination2.pageSize,
  };
  const params = Object.assign(tempParams, formState);
  delete params.orderDeliveryDate;  
  let res = await gerProductionSchedulingLogList(tempParams);
  // psPlanningSchedulingOrderContentTable.dataSource = psPlanningSchedulingOrderContent.value!.getTableData();
  productionSchedulingLogTable.dataSource = res.records;
  pagination2.total = res.total;
}
// 当前页数归类为1 后调列表数据
function getList() {
  pagination.current = 1;
  getSchedulingList();
}
function pageChange({ current, pageSize }) {
  pagination.current = current;
  pagination.pageSize = pageSize;
  getSchedulingList();
}
function pageChange2({ current, pageSize }) {
  pagination2.current = current;
  pagination2.pageSize = pageSize;
  getSchedulingListTwo();
}
function getList2() {
  pagination2.current = 1;
  getSchedulingListTwo();
}
//表单提交事件
async function requestAddOrEdit() {
  let values = await validate();
  try {
    // 表单内容
    let data = getFieldsValue();
    // 排产需求内容
    let tableArr = psPlanningSchedulingOrderContent.value!.getTableData();
    tableArr.map((item) => {
      delete item.id;
    });
    data.psPlanningSchedulingOrderContentList = tableArr;
    //提交表单
    await saveOrUpdate(data, false);
    //刷新列表
    emit("success");
  } finally {
  }
}
const [materialRegModal, { openModal: openMaterialModal }] = useModal();
const [
  psAlwaysSchedulingRegModal,
  { openModal: openpsAlwaysSchedulingModal },
] = useModal();
// const [planOrderResultRegModal, { openModal: openPlanOrderResultModal }] = useModal();
const [mpsItemRegModal, { openModal: openMpsListModal }] = useModal();
const [orderRegModal, { openModal: openOrderListModal }] = useModal();
const [arrangementPlanRegModal, { openModal: openArrangementPlanModal }] = useModal();
const [registerPlanOrderModal, { openModal: openPlanOrderModal }] = useModal();
const [registerMOListModal, { openModal: openMOListModal }] = useModal();
const [registerPlanningSchdulingEdit,{openModal:openPlanningSchdulingEditModal}] = useModal();

const getBindValue = Object.assign({}, "");

function openPsAlwaysScheduling() {
  openpsAlwaysSchedulingModal(true, {
    isUpdate: false,
    showFooter: true,
    type: 1,
  });
}
// 特殊处理 修改交期的提交
function valueChange(item) {
  saveOrUpdate(item.row, true);
}
// 编辑子表
function handleEdit(data) {
  openPlanningSchdulingEditModal(true,data);
}
// 根据id删除一条子表
async function handleDelete(row) {  
  let params = row.map(item => {
    return item.id
  });
  // let params = [data.id];
  await schedulingDel(params);
  getSchedulingList();
}
function masterPlanOpen(model) {
  switch (model.billType) {
    case 1:
      openPlanOrderModal(true, {
        isUpdate: true,
        showFooter: false,
      });
      break;
    case 2:
      openOrderListModal(true, {
        isUpdate: false,
        showFooter: true,
      });
      break;
    case 3:
      openMOListModal(true, {
        isUpdate: false,
        showFooter: true,
      });
      break;
    default:
      $message.createMessage.warn("请先选择计划方法");
      break;
  }
}
// MO订单列表选择
async function MOListhandleSuccess(val, values) {
  const codeArr: Array<string> = [];
  const items: any[] = [];
  let data = getFieldsValue();    
  val.forEach((v) => {
    codeArr.push(v.item.moU9No);
    const item = {
      srcDocNo: v.item.moU9No,
      srcDocLineNo: 10,
      srcDocType: data.billType,
      productCode: v.item.partCode,
      productName: v.item.partName,
      orderDeliveryDate: v.item.u9StartTime.substr(0, 10),
      orderQuantity: v.item.planQTy,
      actualProductionScheduling: v.item.notFinishQty,
    };
    items.push(item);
  });
  setFieldsValue({
    billCode: codeArr.toString(),
    masterPlanId: values.toString(),
  });
  // psPlanningSchedulingOrderContent.value.addRows(items);
  // 触发新增方法
  await schedulingOrderContentTableAdded(items);
  await getSchedulingList();
}

//料品选择回写
function materialhandleSuccess(val, values) {
  psPlanningSchedulingOrderContentTable.dataSource = psPlanningSchedulingOrderContent.value!.getTableData();
  psPlanningSchedulingOrderContentTable.dataSource[index].productName = val[0].label;
  psPlanningSchedulingOrderContentTable.dataSource[index].productCode = val[0].item.code;
  psPlanningSchedulingOrderContentTable.dataSource[index].productId = val[0].value;
}
// mps筛选回写
function mpsItemhandleSuccess(val, values) {
  let ids = values.toString();
  let codeArr = [];
  val.forEach((v) => {
    codeArr.push(v.item.mainPlanCode);
  });
  setFieldsValue({
    billCode: codeArr.toString(),
    masterPlanId: ids,
  });
  getMpsDetail(ids);
}
// 获取Mps详情
async function getMpsDetail(ids) {
  let res = await getMpsItemByMainIds({
    ids: ids,
  });
  res.map((item) => {
    item.orderRowNum = item.rowNum;
    item.orderCenterId = item.id;
    delete item.id;
  });
  psPlanningSchedulingOrderContentTable.dataSource = psPlanningSchedulingOrderContent.value!.getTableData();
  psPlanningSchedulingOrderContentTable.dataSource = res;
}
// mrp运算结果筛选
async function PlanOrderhandleSuccess(val, values) {  
  const codeArr: Array<string> = [];
  const items: any[] = [];
  let data = getFieldsValue();    
  val.forEach((v) => {
    // 表单内容
    let data = getFieldsValue();
    codeArr.push(v.item.billCode);
    const item = {
      billType: data.billType,
      srcDocId: v.item.mrpResultCode,
      srcDocNo: v.item.mrpResultCode,
      srcDocLineNo: 10,
      srcDocType : data.billType,
      productCode: v.item.materialCode,
      productId: v.item.materialId,
      productName: v.item.materialName,
      orderDeliveryDate: v.item.demandDate,
      orderQuantity: v.item.adjustedMrpQuantity,
      // lastEndDischarge: "",
      // totalProduction: v.item.adjustedMrpQuantity,
      actualProductionScheduling: v.item.adjustedMrpQuantity,
      orderRowNo: v.item.orderRowNumber,
      orderNo: v.item.orderBillCode,
    };
    items.push(item);
  });
  setFieldsValue({
    billCode: codeArr.toString(),
    masterPlanId: values.toString(),
  });
  // psPlanningSchedulingOrderContentTable.dataSource = items;
  // 触发新增方法
  await schedulingOrderContentTableAdded(items);
  await getSchedulingList();
}
// 总装排产计划回写
function arrangementPlanhandleSuccess(val, values, type) {
  let ids = values.toString();
  let codeArr = [];
  val.forEach((v) => {
    codeArr.push(v.item.schedulingCode);
  });
  setFieldsValue({
    billCode: codeArr.toString(),
    masterPlanId: ids,
  });
  getArrangementDetail(ids);
}
// 获取总装排产详情
async function getArrangementDetail(ids) {
  let res = await getArrangementItemByMainIds({
    ids: ids,
  });
  res.map((item) => {
    item.orderRowNum = item.rowNum;
    item.orderCenterId = item.id;
    delete item.id;
  });
  psPlanningSchedulingOrderContentTable.dataSource = psPlanningSchedulingOrderContent.value!.getTableData();
  psPlanningSchedulingOrderContentTable.dataSource = res;
}
//订单回写
async function orderhandleSuccess(val, values, type) {
  psPlanningSchedulingOrderContentTable.dataSource = psPlanningSchedulingOrderContent.value!.getTableData();
  let tempArr = [];
  let codeArr = [];
  let data = getFieldsValue();    
  // 表单内容
  val.forEach((v) => {
    codeArr.push(v.item.billCode);
    tempArr.push({
      billType: data.billType,
      PlanOrderCode: "",
      srcDocId: v.item.id,
      srcDocNo: v.item.billCode,
      srcDocType : data.billType,
      srcDocLineNo: v.item.rowNum,
      productCode: v.item.materialCode,
      productId: v.item.materialId,
      productName: v.item.materialName,
      orderDeliveryDate: v.item.orderDeliveryDate,
      orderQuantity: v.item.orderQuantity,
      lastEndDischarge: "",
      totalProduction: "",
      actualProductionScheduling: v.item.ableProductQuantity,
      unProductionScheduling: v.item.orderQuantity,
      orderNo: v.item.billCode,
      orderRowNo: v.item.rowNum,
    });
  });
  setFieldsValue({
    billCode: codeArr.toString(),
    masterPlanId: values.toString(),
  });
  // psPlanningSchedulingOrderContentTable.dataSource = tempArr;
  // 触发新增方法
  await schedulingOrderContentTableAdded(tempArr);
  await getSchedulingList();
}

function psAlwaysSchedulinghandleSuccess(val) {
  setFieldsValue({
    productionSchedulingScheme: val[0].label,
    productionSchedulingSchemeId: val[0].value,
  });
}
// 下发计划
const clickDistributePlan = async () => {
  await distributePlan({
    id: propsData.planId,
  }).catch((err) => {
    console.error(err);
  });
  //刷新列表
  emit("success");
};
// 模拟排产
const clickSimulatedScheduling = async () => {
  openFullLoading();
  try {
    let data = getFieldsValue();
    // 模拟排产
    // await getSimulatedScheduling({
    //   id: data.id.toString(),
    // });
  } finally {
    closeFullLoading();
  }
};
// 排产作业按钮
async function clickSchedulingOperation() {
  let values = await validateFields(["productionSchedulingScheme"]);
  openFullLoading();
  try {
    let data = getFieldsValue();
    let tempIdArr = [];
    await preCalculate({
      productionSchedulingSchemeId: data.productionSchedulingSchemeId,
    });
    closeFullLoading();
  } finally {
    closeFullLoading();
  }
}
// 新增按钮
function clickSchedulingTableAdd() {
  const records: any[] = [];
  let tempObj = {
    PlanOrderCode: "",
    srcDocId: "",
    srcDocNo: "",
    srcDocLineNo: "",
    productCode: "",
    srcDocType: "",
    productName: "",
    orderDeliveryDate: "",
    orderQuantity: "",
    lastEndDischarge: "",
    totalProduction: "",
    actualProductionScheduling: "",
    unProductionScheduling: "",
  };
  records.push(tempObj);
  psPlanningSchedulingOrderContent.value.addRows(records);
}
// 删除按钮
async function clickSchedulingTableDel() {
  // 获取选中的列
  let selectData = psPlanningSchedulingOrderContent.value.getSelectionData();
  if (selectData.length > 0) {
    let ids = [];
    selectData.forEach((item) => {
      ids.push(item.id);
    });
    // 删除数据库数据
    await schedulingDel(ids);
    // 删除界面数据
    // psPlanningSchedulingOrderContent.value.removeSelection();
    await getSchedulingList();
  } else $message.createMessage.warn("请先选择数据");
}
async function schedulingOrderContentTableAdded(rows) {
  rows.map((item) => delete item.id);
  //添加完成
  let res = await saveOrUpdate(rows, false);
}
</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-calendar-picker) {
  width: 100%;
}
.mgl-15 {
  margin-left: 15px;
}
.scheduling_box {
  padding: 20px 10px;
  background-color: #fff;
}
:deep(.my_tabs .ant-tabs-nav-wrap) {
  // flex: 0.1 !important;
}
</style>
